/*
 *	Author: Vitaly Rozhkov
 *	vitaly.rozhkov@gmail.com
 *  http://bookvarius.livejournal.com
 *
*/

#include "Batch Helpers/include/common.jsx"

var configFilePath =  app.path.toString() + "/Presets/Scripts/Batch Helpers/config/ResizeForWebCfg.txt";
var settings;

function _readSettings(silent){
	settings = ConfigRead(configFilePath);
	if(	null == settings || 
		(!settings['webWidth'].isInteger() || 
		!settings['webHeight'].isInteger() )
	)
	{
		if(!silent){
			alert('Use default settings: 900x600');
		}
		if(null == settings){
			settings = new Array();
		}
		settings['webWidth'] = 900;
		settings['webHeight'] = 600;
	}
}

function _checkSize(img, silent) {
	if(null == img){
		img = app.activeDocument;
	}
	
	var type = getImgType(img);
	var enlargeConfirm = 0;
	var proportionsConfirm = 0;
	var res = 0;

	switch(type){
		case imageTypes.LANDSCAPE:
			if(img.width != settings['webWidth']){
				if(img.width < settings['webWidth']) {
					enlargeConfirm = 1;
				}
				/*
				if(Math.round(img.width/img.height) != Math.round(3/2)){
					proportionsConfirm = 1;
				}
				*/
			}
			break;
		case imageTypes.PORTRAIT:
			if(img.height != settings['webHeight']){
				if(img.height < settings['webHeight']) {
					enlargeConfirm = 1;
				}
				/*
				if(Math.round(img.height/img.width) != Math.round(3/2)){
					proportionsConfirm = 1;
				}
				*/
			}
			break;
	}

	if(!silent && enlargeConfirm){
		if(!confirm('Are you sure want to enlarge image ' + Number(img.width) + 'x' + Number(img.height) + ' px to ' + settings['webWidth'] + 'x' + settings['webHeight'] + 'px ?')){
			res = -1;
		}
	}	
	if(!silent && res != -1 && proportionsConfirm){
		if(!confirm('Your image doesn\'t have 3/2 proportions: ' + Number(img.width) + 'x' + Number(img.height) + " px\n" + "Do you want to resize it as a common one?")){
			res = -1;
		}
	}
	return res;
}

function _resizeImg(img, silent) {
	if(null == img){
		img = app.activeDocument;
	}
	
	var type = getImgType(img);
	switch(type){
		case imageTypes.SQUARE:
		case imageTypes.LANDSCAPE:
			img.resizeImage(Number(settings['webWidth']), null, null, ResampleMethod.BICUBIC);
			break;
		case imageTypes.PORTRAIT:
			img.resizeImage(null, Number(settings['webHeight']), null, ResampleMethod.BICUBIC);
			break;
	}
}

/*---------------- interface functions ----------------------*/

function Resize(img, silent){
	if(null == silent){
		silent = 0;
	}
	_readSettings(silent);
	
	var img = app.activeDocument;
	if(0 != _checkSize(img, silent)){
		return -1;
	}

	return _resizeImg(img, silent);
}




